//
//  HouseImagesViewController.m
//  YaDiuDiu
//
//  Created by 欧洪飞 on 2017/10/10.
//  Copyright © 2017年 jy. All rights reserved.
//

#import "HouseImagesViewController.h"

@interface HouseImagesViewController ()<UIImagePickerControllerDelegate,UINavigationControllerDelegate,UIScrollViewDelegate>
{
    UIImagePickerController *imagepc;
    UIImageView *imageView;
    
    UIScrollView *sclView;//
    UIPageControl *pagectl;
    NSInteger page;//当前页码
    UILabel *lab;//页数
}
@property (nonatomic,strong)NSMutableArray *array;
@property (nonatomic,strong)NSMutableArray *arrImgUrl;
@property (nonatomic,copy)NSString *imgUrl;

@end

@implementation HouseImagesViewController

- (void)viewDidLoad {
    [super viewDidLoad];

    
    [self setBGColor];
    [self showNav:@"图片编辑"];
    _array = [NSMutableArray array];
    _arrImgUrl = [NSMutableArray array];
    [self loadUI];
    
}

- (void)loadUI{
    sclView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 64, ScreenWidth, 200)];
    sclView.delegate = self;
    sclView.pagingEnabled = YES;
    sclView.backgroundColor = [UIColor grayColor];
    [self.view addSubview:sclView];
    
    for (NSInteger i = 0; i<_images.count; i++) {
        imageView = [[UIImageView alloc] initWithFrame:CGRectMake(i*ScreenWidth, 0, ScreenWidth, 200)];
        [imageView sd_setImageWithURL:[NSURL URLWithString:_images[i]] placeholderImage:[UIImage imageNamed:@""]];
        [sclView addSubview:imageView];
    }
    //赋值
    if (_images.count > 0) {
        _arrImgUrl = _arrayImgUrl;
    }
    
    UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
    btn.frame = CGRectMake(16, 64+210, 70, 70);
    [btn setImage:[UIImage imageNamed:@"sptp"] forState:UIControlStateNormal];
    [btn addTarget:self action:@selector(clickAdd) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:btn];
    
    UILabel *labTit = [[UILabel alloc] init];
    labTit.text = @"注：选择的第一张为封面，最多上传6张。";
    labTit.textColor = [UIColor lightGrayColor];
    labTit.font = [UIFont systemFontOfSize:14.0];
    labTit.numberOfLines = 0;
    [self.view addSubview:labTit];
    [labTit makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(btn.right).offset(8);
        make.centerY.equalTo(btn.centerY);
        make.right.equalTo(self.view.right).offset(-8);
    }];
    
    UIButton *btn2 = [UIButton buttonWithType:UIButtonTypeCustom];
    btn2.frame = CGRectMake(0, ScreenHeight-45, ScreenWidth, 45);
    btn2.backgroundColor = [UIColor redColor];
    [btn2 setTitle:@"完成" forState:UIControlStateNormal];
    [btn2 setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    btn2.titleLabel.font = [UIFont systemFontOfSize:17.0];
    [btn2 addTarget:self action:@selector(clickFinish) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:btn2];
    
}

#pragma -mark UIScrollViewDelegate
-(void)scrollViewDidScroll:(UIScrollView *)scrollView{
    
    page = (int)(scrollView.contentOffset.x/scrollView.bounds.size.width + 0.5);
    lab.text = [NSString stringWithFormat:@"%li/%li",page+1,_array.count];
    pagectl.currentPage = page;
}

- (void)clickFinish{
    [self.navigationController popViewControllerAnimated:YES];
    if (_arrImgUrl.count == 0) {
        return;
    }
    
    NSLog(@"arrimgUrl:%@",_arrImgUrl);
    [self.delegate sendImgUrl:_arrImgUrl];
}

- (void)clickAdd{
    if (_array.count >= 6) {
        [self showAlert:@"不能添加更多照片"];
        return;
    }
    
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
    
    UIAlertAction *action1 = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];
    
    UIAlertAction *action2 = [UIAlertAction actionWithTitle:@"拍照" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [self pickerPicture];
    }];
    
    UIAlertAction *action3 = [UIAlertAction actionWithTitle:@"从相册中获取" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [self pickerPictureFromAlbum];
    }];
    
    [alert addAction:action1];
    [alert addAction:action2];
    [alert addAction:action3];
    [self presentViewController:alert animated:YES completion:nil];
}
//拍照获取
- (void)pickerPicture{
    if ([UIImagePickerController isCameraDeviceAvailable:UIImagePickerControllerCameraDeviceRear]) {
        NSLog(@"用前置摄像头");
        imagepc = [[UIImagePickerController alloc] init];
        imagepc.sourceType = UIImagePickerControllerSourceTypeCamera;
        imagepc.delegate = self;
        imagepc.allowsEditing = YES;
        imagepc.cameraDevice = UIImagePickerControllerCameraDeviceRear;
        
    }else if ([UIImagePickerController isCameraDeviceAvailable:UIImagePickerControllerCameraDeviceFront]){
        NSLog(@"用后置摄像头");
        imagepc = [[UIImagePickerController alloc] init];
        imagepc.cameraDevice = UIImagePickerControllerCameraDeviceFront;
    }else{
        UIAlertController *a = [UIAlertController alertControllerWithTitle:@"调用失败" message:@"请从手机相册中选择" preferredStyle:UIAlertControllerStyleAlert];
        [self presentViewController:a animated:YES completion:nil];
    }
    
    [self presentViewController:imagepc animated:YES completion:nil];
}

//从手机的图片获取
- (void)pickerPictureFromAlbum{
    UIImagePickerController *imgpicker = [[UIImagePickerController alloc] init];
    imgpicker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
    imgpicker.allowsEditing = YES;
    imgpicker.delegate = self;
    [self presentViewController:imgpicker animated:YES completion:nil];
}

#pragma -mark UIImagePickerControllerDelegate
-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info{
    UIImage *img = [info objectForKey:UIImagePickerControllerEditedImage];
    [self loadImage:img];
    [self dismissViewControllerAnimated:YES completion:nil];
}

-(void)imagePickerControllerDidCancel:(UIImagePickerController *)picker{
    [self dismissViewControllerAnimated:YES completion:nil];
}

//图片上传
- (void)loadImage:(UIImage *)image{
    NSMutableDictionary *parmas = [NSMutableDictionary dictionary];
    [parmas setObject:@"pic.png" forKey:@"pic"];
    [parmas setObject:@"name" forKey:@"name"];
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    NSString *url = [NSString stringWithFormat:@"%@/App/Norm/upload",urlHead];
    [manager POST:url parameters:parmas constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
        NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
        formatter.dateFormat = @"yyyy-MM-dd HH:mm:ss";
        NSString *fileName = [NSString stringWithFormat:@"%@.png",[formatter stringFromDate:[NSDate date]]];
        NSData *data = UIImageJPEGRepresentation(image, 0.5);
        [formData appendPartWithFileData:data name:@"pic" fileName:fileName mimeType:@"image/png"];
        [formData appendPartWithFileData:data name:@"name" fileName:fileName mimeType:@"image/png"];
        
    } success:^(AFHTTPRequestOperation *operation, id responseObject) {
        NSDictionary *op = [NSJSONSerialization JSONObjectWithData:responseObject options:kNilOptions error:nil];
        NSLog(@"dic:%@",op);
        NSString *error = [NSString stringWithFormat:@"%li",[[op objectForKey:@"error"] integerValue]];
        if ([error integerValue] == 200) {
            _imgUrl = [op objectForKey:@"result"];
            [_arrImgUrl addObject:_imgUrl];
            NSString *str = [NSString stringWithFormat:@"%@%@",[user objectForKey:@"ImageUrl"],_imgUrl];
            [_array addObject:str];
            
            sclView.contentSize = CGSizeMake(ScreenWidth*_array.count, 200);
            
        }
        
        for (NSInteger i = 0; i<_array.count; i++) {
            imageView = [[UIImageView alloc] init];
            NSString *str = [NSString stringWithFormat:@"%@",_array[i]];
            [imageView sd_setImageWithURL:[NSURL URLWithString:str] placeholderImage:[UIImage imageNamed:@""]];
            imageView.frame = CGRectMake(i*ScreenWidth, 0, ScreenWidth, 200);
            [sclView addSubview:imageView];
            
            UIButton *btnDel = [UIButton buttonWithType:UIButtonTypeCustom];
            btnDel.frame = CGRectMake(ScreenWidth-40, 64+10, 30, 30);
            [btnDel setImage:[UIImage imageNamed:@"x-拷贝"] forState:UIControlStateNormal];
            btnDel.backgroundColor = [UIColor whiteColor];
            btnDel.layer.cornerRadius = 10.0;
            [btnDel addTarget:self action:@selector(clicks) forControlEvents:UIControlEventTouchUpInside];
            [self.view addSubview:btnDel];
            
        }
        
        lab = [[UILabel alloc] initWithFrame:CGRectMake(ScreenWidth-50, 150+64, 30, 30)];
        lab.text = [NSString stringWithFormat:@"1/%li",_array.count];
        lab.textAlignment = NSTextAlignmentCenter;
        lab.backgroundColor = [UIColor grayColor];
        lab.textColor = [UIColor redColor];
        lab.layer.masksToBounds = YES;
        lab.layer.cornerRadius = 15.0;
        [self.view addSubview:lab];
        
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        NSLog(@"error:%@",error);
    }];
    
}
//删除图片
- (void)clicks{
    NSLog(@"page:%li",(long)page);
    
    NSString *files = _arrImgUrl[page];
    NSLog(@"file:%@",files);
    NSMutableDictionary *parmas = [NSMutableDictionary dictionary];
    [parmas setObject:files forKey:@"files"];
    NSString *url = [NSString stringWithFormat:@"%@/App/Norm/delfile",urlHead];
    [[AFHTTPSessionManager manager] POST:url parameters:parmas success:^(NSURLSessionDataTask *task, id responseObject) {
        NSLog(@"删除图片res:%@",responseObject);
        NSString *error = [NSString stringWithFormat:@"%li",[[responseObject objectForKey:@"error"] integerValue]];
        if ([error integerValue] == 200) {
            
            [_array removeObjectAtIndex:page];
            [_arrImgUrl removeObjectAtIndex:page];
            sclView.contentSize = CGSizeMake(ScreenWidth*_array.count, 200);
            lab.text = [NSString stringWithFormat:@"%li/%li",page+1,_array.count];
            //lab.text = [NSString stringWithFormat:@"%li/%li",];
        }
        
    } failure:^(NSURLSessionDataTask *task, NSError *error) {
        NSLog(@"error:%@",error);
    }];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
